var md5Encrypt = require("../../../util/md5/md5.js");

Page({
  data: {
    addUrl: "",
    imgUrl: "",
    order_id: "",
    bill: [],
    depositState: "", //-1不免，0半免，1全免
    money: {
      //金额
      price1: "",
      price2: "",
    },
    // isLoadFlag: false,
    // _yihuan: 0,
    goodsInfo: null,
    isShowToubao: false,
    isSelectAll: false,
    // billids: [], //待还款 ids
    selectbillids: [], //已选待还款 ids
    total: "", //还款金额
    stageNum: 0, //期数
    isShowHuankuan: false, //还款弹出框
    selectbill: [], //已选列表
    amount_override: 0, //应还逾期金额
    safe_bill: null, // 碎屏险
    isSelectScreen: false,
    isShowDownPayment: false, // 是否显示首期款弹窗
    downPaymentKey: [], //首期款key
    downPaymentValue: {}, // 首期款数据
    hideOneClickPayment: false // 隐藏一键支付
  },

  // 支付碎屏险
  payScreenBreakage() {
    const { isSelectScreen } = this.data
    if(!isSelectScreen) {
      my.showToast({
        type: 'none',
        content: '请选择意外保障险',
        duration: 3000
      })
      return
    }
    const app = getApp()
    const { testUrl, user_id: zm_user_id } = app.globalData
    const { order_id } = this.data
    my.showLoading({
      content: "请稍后",
      delay: 0,
    });
    my.request({
      url: `${testUrl}//api/order/payOrderSafeBill`,
      method: 'POST',
      data: {
        order_id,
        zm_user_id
      },
      success: (res) => {
        const { code, msg: content, data: tradeNO } = res.data
        if(code !== 1) {
          my.showToast({
            type: 'none',
            content
          })
        }
        my.tradePay({
          tradeNO,
          success: (res) => {
            const { resultCode } = res
            console.log(resultCode, 'resultCode');
            if(resultCode === '9000') {
              my.showToast({
                type: "success",
                content: "支付成功!",
                duration: 3000,
              });
              this.showBill("load");
            } else if (resultCode == '4000') {
              my.showToast({
                type: "none",
                content: "支付失败",
                duration: 3000,
              });
            }
          },
          fail: () =>{
            my.showToast({
              type: "none",
              content: "支付失败",
              duration: 800,
            });
          }
        })
      },
      complete: () => {
        my.hideLoading();
      }
    })
  },


  handleDownPayment(e) {
    const { state } = e.target.dataset
    this.setData({
      isShowDownPayment: parseInt(state) || false
    })
    const { 
      order_down_payment_detail,
      fq_status
     } = this.data.bill[0]
     const downPaymentKey = Object.keys(order_down_payment_detail)
     if(fq_status === 1 || fq_status === 5 ) {
      this.setData({
        hideOneClickPayment: true
      })
     } else {
      this.setData({
        hideOneClickPayment: false
      })
     }
     this.setData({
      downPaymentValue: order_down_payment_detail,
      downPaymentKey
     })
     
  },

  // 选中碎屏险
  selectScreenbreakage() {
    // const { isSelectScreen } = this.data
    this.setData({
      isSelectScreen: true,
      stageNum: 0,
      total:'',
      selectbillids: [],
      selectbill: [],
      amount_override: 0
    })
  },

  //获取账单信息
  showBill(action) {
    const { testUrl, imgUrl, device, signType, order_id, version } =
      getApp().globalData;

    this.setData({
      imgUrl,
    });

    const billParam = {
      version,
      device,
      signType,
      order_id, //订单号
    };
    const token = md5Encrypt.md5(billParam);

    my.request({
      url: `${testUrl}/api/order/getOrderBillDetail`,
      method: "POST",
      data: {
        version,
        device,
        signType,
        order_id: this.data.order_id, //订单号
        token,
      },
      dataType: "json",
      success: (res) => {
        console.log(res.data, 'res');
        const {
          data: {
            data: { row, detail: goodsInfo,safe_bill },
            code,
            msg
          },
        } = res;
        if (code === 1) {

          let bill = row.map((arr) => {
            // const { last_repayment_time } = arr
            // if(last_repayment_time) {
            //   arr.last_repayment_time = last_repayment_time.split(" ")[0];
            // }
            const ifState = {
              1: "待还款",
              2: "已还款",
              3: "逾期中",
              4: "异常退货",
              5: "已退款",
            };

            arr.fq_statusName = ifState[arr.fq_status];

            return arr;
          });

          const {
            order_down_payment_prompt,
            fq_status
          } = bill[0]
          if(order_down_payment_prompt && fq_status === 1) {
            bill[0].fq_statusName = '待支付'
          }
          if(order_down_payment_prompt && fq_status === 2) {
            bill[0].fq_statusName = '已支付'
          }

          this.setData({
            bill,
            safe_bill,
            goodsInfo,
          });
        } else {
          my.showToast({
            type: 'none',
            content: msg,
            duration: 3000
          })
        }
      },
      complete: function () {
        if (action == "load") {
          my.hideLoading();
        } else if (action == "pulldown") {
          setTimeout(function () {
            my.stopPullDownRefresh(); //停止刷新
          }, 1000);
        }
      },
    });
  },

  onLoad(option) {
    my.setNavigationBar({
      frontColor: "#000000",
      backgroundColor: "#f6f6f6",
    });
    //加载动画
    // my.showLoading({
    //   content: "加载中...",
    //   delay: 0,
    // });

    var order_id = option.order_id; //订单号
    this.setData({
      order_id,
    });
    const { platform } = option
    let app = getApp()
    app.setShareChannel(platform)
  },

  onReady() {
    this.showBill("load");
  },

  //下拉刷新
  onPullDownRefresh() {
    this.showBill("pulldown");
  },

  // 详情跳转
  toGoodsDetail(e) {
    my.navigateTo({
      url:
        "../../rent/goodsdetail/goodsdetail?id=" +
        e.currentTarget.dataset.goods_id,
    });
  },

  // showtoubao() {
  //   this.setData({
  //     isShowToubao: true
  //   })
  // },

  closetoubao(e) {
    this.setData({
      isShowToubao: false,
    });
  },

  // 账单期数点击
  clickItem(e) {

    const { id } = e.currentTarget.dataset;
    const res = this.data.bill.find(({ id: listId }) => {
      return listId === id;
    });
    
    const { amount_override, total_pay: total } = res;
    this.setData({
      stageNum: 1, // 期数
      total, // 应还金额
      selectbillids: [id],
      selectbill: [res], // 选择账单
      amount_override, //逾期金额
      isSelectScreen: false // 碎屏险
    });
  },

  // countMoney(ids) {
  //计算金额
  // let _total = 0;
  // let _amount_override = 0; // 逾期金额
  // let _selectbill = []; // 选择账单
  // console.log(ids, "ids");
  // ids.forEach((iarr) => {
  //   this.data.bill.forEach((barr) => {
  //     if (barr.id == iarr) {
  //       _selectbill.push(barr);
  //       _total +=
  //         parseFloat(barr.total_pay) + parseFloat(barr.amount_override);
  //       _amount_override += parseFloat(barr.amount_override);
  //     }
  //   });
  // });
  // this.setData({
  //   stageNum: ids.length, // 期数
  //   total: parseFloat(_total).toFixed(2), // 应还金额
  //   selectbill: _selectbill, // 选择账单
  //   amount_override: _amount_override, //逾期金额
  // });
  // },

  // 还款弹出框
  showhuankuan() {
    const { selectbill, bill } = this.data
    if (!selectbill[0].is_able_payment_bill) {
      const res = bill.find((item) => item.is_able_payment_bill === 1)
      if(!res) { // 如果没找到可归还的期数，则返回undefined，不处理直接提示
        my.showToast({
          type: 'none',
          content: '暂无期数可还款'
        })
        return
      }
      const {  current_tenancy_term } = res
      my.showToast({
        type: "none",
        content: `请先支付第${current_tenancy_term}期账单！`,
      });
      return;
    }
    this.setData({
      isShowHuankuan: true,
    });
  },

  //还款弹出框
  hidehuankuan() {
    this.setData({
      isShowHuankuan: false,
    });
  },

  //确认还款
  repayment() {
    let vm = this;
    let app = getApp();
    my.showLoading({
      content: "请稍后",
      delay: 0,
    });
    my.request({
      url: app.globalData.testUrl + "/Api/order/StagesPay",
      method: "POST",
      data: {
        order_id: vm.data.order_id,
        stages_id: vm.data.selectbillids.join(","),
      },
      success: (res) => {
        my.hideLoading();
        if (res.data.status == "1001") {
          let _tradeNO = res.data.data;
          my.tradePay({
            tradeNO: _tradeNO,
            success: function (res) {
              if (res.resultCode == 9000) {
                my.navigateTo({
                  url: "../success/success?typeindex=4",
                });
                vm.setData({
                  isShowHuankuan: false,
                  isShowDownPayment: false
                });
              } else if (res.resultCode == 4000) {
                my.showToast({
                  type: "none",
                  content: "支付失败",
                  duration: 800,
                });
              }
            },
            fail: function () {
              my.showToast({
                type: "none",
                content: "支付失败",
                duration: 800,
              });
            },
          });
        } else if (res.data.status == "101") {
          my.showToast({
            type: "none",
            content: res.data.msg,
            duration: 800,
          });
        } else {
          my.showToast({
            type: "none",
            content: "系统繁忙,请稍后从事",
            duration: 800,
          });
        }
      },
      complete: () => {
        my.hideLoading();
      },
    });
  },
});
